package xyz.fivefaith.tool.common.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
import ognl.enhance.ExpressionAccessor;

/**
 * ognl工具类
 *
 * @author zhaoanchi
 * @version 1.0
 * @since 1.1.0
 */
@Slf4j
@UtilityClass
public class OgnlUtil {

    public static Object getValue(String expression, Object root) {
        try {
            return Ognl.getValue(expression, root);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static <T> T getValue(String expression, Object root, Class<T> clazz) {
        try {
            return (T) Ognl.getValue(expression, root, clazz);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static Object getValue(String expression, OgnlContext context, Object root) {
        try {
            return Ognl.getValue(expression, context, root);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static <T> T getValue(
            String expression, OgnlContext context, Object root, Class<T> resultType) {
        try {
            return (T) Ognl.getValue(expression, context, root, resultType);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static Object getValue(Object tree, Object root) {
        try {
            return Ognl.getValue(tree, root);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static <T> T getValue(Object tree, Object root, Class<T> resultType) {
        try {
            return (T) Ognl.getValue(tree, root, resultType);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static Object getValue(Object tree, OgnlContext context, Object root) {
        try {
            return Ognl.getValue(tree, context, root);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static <T> T getValue(
            Object tree, OgnlContext context, Object root, Class<T> resultType) {
        try {
            return (T) Ognl.getValue(tree, context, root, resultType);
        } catch (OgnlException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static Object getValue(ExpressionAccessor expression, OgnlContext context, Object root) {
        return Ognl.getValue(expression, context, root);
    }

    public static <T> T getValue(
            ExpressionAccessor expression, OgnlContext context, Object root, Class<T> resultType) {
        return (T) Ognl.getValue(expression, context, root, resultType);
    }
}
